package mspdt.ubzuuch.mn;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ExpandableListView;
import android.widget.Toast;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.TextView;

public class MainActivity extends Activity {

	private ExpandableListView expList_trade;
	private ArrayList<String> parent_datas = new ArrayList<String>();
	  private ArrayList<Integer> parent_counts = new ArrayList<Integer>();
	  private ArrayList<ArrayList<String>> child_datas = new ArrayList<ArrayList<String>>();
	  private ArrayList<ArrayList<Integer>> child_counts = new ArrayList<ArrayList<Integer>>();
	  private ArrayList<ArrayList<Integer>> child_ids = new ArrayList<ArrayList<Integer>>();
	  private MainExpandableAdapter main_adapter;
	  private String url = "";
	  private String[] p_names = {"Орон сууц", "Барилга", "Хашаа байшин", "Зуслан"};
	  private String[][] child_names = {{"1 өрөө", "2 өрөө", "3 өрөө", "4+ өрөө", "Зарагдсан"},
			  {"Амины орон сууц","Обьект","Үйлчилгээний байр","Газар","Зарагдсан"},
			  {"15 сая төгрөг хүртэл","15-30 сая төгрөг хүртэл","30 саяас дээш","Үйлчилгээтэй хашаа байшин","Зарагдсан"},
			  {"30 сая хүртэл","30-60 сая хүртэл","60 саяас дээш","Зуслангын газар","Зарагдсан"}};
	private NetworkConnectionClass network;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		network= new NetworkConnectionClass(this);
		expList_trade = (ExpandableListView)findViewById(R.id.exp_list_trade);
		expList_trade.setGroupIndicator(null);
		expList_trade.setOnChildClickListener(new OnChildClickListener() {
			
			@Override
			public boolean onChildClick(ExpandableListView parent, View v,
					int groupPosition, int childPosition, long id) {
				// TODO Auto-generated method stub
				//Child дээр дарахад тухайн child-н ID гаар нь дараагын дэлгэрэнгүйг харах
				if(child_counts.get(groupPosition).get(childPosition)>0)
				{
					if(childPosition!=4)
					{
						if(childPosition==3 && groupPosition==0)
						{
							String child = "4 өрөө";
							url = "http://202.131.237.185/ubzuuch/web/banner/getbair?roomnum="+child+
									"&category=1"+"&page=1";
						}
						else
						url = "http://202.131.237.185/ubzuuch/web/banner/getbair?roomnum="+child_datas.get(groupPosition).get(childPosition)+
								"&category=1"+"&page=1";
					}
						
					else
						url = "http://202.131.237.185/ubzuuch/web/banner/getbair?roomnum="+"харах"+
						"&category=1"+"&page=1"+"&type="+(groupPosition+1);
					
					Intent intent = new Intent(MainActivity.this, ItemActivity.class);
					Bundle bundle = new Bundle();
					bundle.putInt("title", R.id.title_menu_1);
					bundle.putString("URL", url);
					intent.putExtras(bundle);
					startActivity(intent);
					overridePendingTransition(R.anim.right_in, R.anim.no_anim);
				}
				else
					Toast.makeText(MainActivity.this, "Мэдээ хоосон байна", 2000).show();
				
				
				return false;
			}
		});
		
		createTitleComponents();
		findViewById(R.id.title_menu_1).setBackgroundResource(R.drawable.text_background);
		focusOnView();
		createExpData();
	}
	public void onResume()
	{
		super.onResume();
		focusOnView();
	}
	private final void focusOnView(){
        new Handler().post(new Runnable() {
            @Override
            public void run() {
            	findViewById(R.id.title_scroll_view).scrollTo(findViewById(R.id.title_menu_1).getLeft()-10, 0);
            }
        });
    }
	public void createExpData()
	{
		//JSON уншаагүй байгаа болохоор тест маягаар гараас шууд өгөгдөл уншиж байгаа Json уншихад Thread доторхыг солино
		parent_counts.clear();
		parent_datas.clear();
		child_datas.clear();
		child_counts.clear();
		child_ids.clear();
		
		final ProgressDialog dialog = ProgressDialog.show(MainActivity.this, null, 
    			getResources().getString(R.string.dialog_please_wait), true);
    	
    			final Handler handler = new Handler() {
    			   public void handleMessage(Message msg) {
    				   if(msg.what==1)
    				   {
    					   main_adapter = new MainExpandableAdapter(MainActivity.this, parent_datas, parent_counts, child_datas, child_counts);
        				   expList_trade.setAdapter(main_adapter);
    				   }
    				   else
    				   {
    					   Toast.makeText(MainActivity.this, "Сервэртэй холбогдоход алдаа гарлаа", 3000).show();
    				   }
    				   dialog.dismiss();
    			      }
    			   };
    			Thread checkUpdate = new Thread() {  
    			   public void run() {
    				   //энэ дотор Json-с дата уншиж харгалзах утгуудад нь хийж өгнө
    				   if(network.isConnectedToServer(MainActivity.this.getResources().getString(R.string.json_main_data_counts)+"1", 5000) && network.isNetworkConnected())
    				   {
    					   for(int i=0;i<p_names.length;i++)
       					{
       						parent_datas.add(p_names[i]);
       						ArrayList<String> child_data = new ArrayList<String>();
       						for(int j=0;j<child_names[i].length;j++)
       						{
       							child_data.add(child_names[i][j]);
       						}
       						child_datas.add(child_data);
       					}
       				   JSONfuncObject json_object = new JSONfuncObject();
       				   JSONObject json_data_obj = json_object.getJSONfromURL(MainActivity.this.getResources().getString(R.string.json_main_data_counts)+"1");
       				   try {
   						JSONArray parent_counts = json_data_obj.getJSONArray(MainActivity.this.getResources().getString(R.string.json_main_get_parent_counts));
   						for(int i=0;i<parent_counts.length();i++)
   						{
   							MainActivity.this.parent_counts.add(parent_counts.getInt(i));
   						}
   						JSONArray zarsan_counts = json_data_obj.getJSONArray(MainActivity.this.getResources().getString(R.string.json_main_get_zarsan_counts));
   						JSONArray apartment_counts = json_data_obj.getJSONArray(MainActivity.this.getResources().getString(R.string.json_main_get_apartment_counts));
   						ArrayList<Integer> child_count_apartment = new ArrayList<Integer>();
   						for(int i=0;i<apartment_counts.length();i++)
   						{
   							child_count_apartment.add(apartment_counts.getInt(i));
   						}
   						child_count_apartment.add(zarsan_counts.getInt(0));
   						child_counts.add(child_count_apartment);
   						
   						
   						
   						JSONArray barilga_counts = json_data_obj.getJSONArray(MainActivity.this.getResources().getString(R.string.json_main_get_barilga_counts));
   						ArrayList<Integer> child_count_barilga = new ArrayList<Integer>();
   						for(int i=0;i<barilga_counts.length();i++)
   						{
   							child_count_barilga.add(barilga_counts.getInt(i));
   						}
   						child_count_barilga.add(zarsan_counts.getInt(1));
   						child_counts.add(child_count_barilga);
   						
   						JSONArray khashaa_counts = json_data_obj.getJSONArray(MainActivity.this.getResources().getString(R.string.json_main_get_khashaa_counts));
   						ArrayList<Integer> child_count_khashaa = new ArrayList<Integer>();
   						for(int i=0;i<khashaa_counts.length();i++)
   						{
   							child_count_khashaa.add(khashaa_counts.getInt(i));
   						}
   						child_count_khashaa.add(zarsan_counts.getInt(2));
   						child_counts.add(child_count_khashaa);
   						
   						JSONArray zuslan_counts = json_data_obj.getJSONArray(MainActivity.this.getResources().getString(R.string.json_main_get_zuslan_counts));
   						ArrayList<Integer> child_count_zuslan = new ArrayList<Integer>();
   						for(int i=0;i<zuslan_counts.length();i++)
   						{
   							child_count_zuslan.add(zuslan_counts.getInt(i));
   						}
   						child_count_zuslan.add(zarsan_counts.getInt(3));
   						child_counts.add(child_count_zuslan);
   						
   					} catch (JSONException e) {
   						// TODO Auto-generated catch block
   						e.printStackTrace();
   					}
       				handler.sendEmptyMessage(1);
    				  }
    				  else
    				  {
    					  handler.sendEmptyMessage(0);  
    				  }
    				   
    				   
    			      }
    			   };
    			checkUpdate.start();
    			
		
	}
	public static String readStream (InputStream in) throws IOException {
	    StringBuffer out = new StringBuffer();
	    byte[] b = new byte[4096];
	    for (int n; (n = in.read(b)) != -1;) {
	        out.append(new String(b, 0, n));
	    }
	    return out.toString();
	}
	public void createTitleComponents()
	{
		//Хуудасны дээр байрлах толгой хэсгийн хийх үйлдлүүд
		
		//Үндсэн товчлууруудын үйлдэл
		//Буцах товчлуур
		findViewById(R.id.back).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
				overridePendingTransition(R.anim.no_anim, R.anim.no_anim);
			}
		});
		//Хадгалсан мэдээ унших товчлуур
		findViewById(R.id.title_history).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				startActivity(new Intent(MainActivity.this, ItemActivityFromDB.class));
				overridePendingTransition(R.anim.top_in, R.anim.no_anim);
			}
		});
		//Хайх товчлуур
		findViewById(R.id.title_search).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				startActivity(new Intent(MainActivity.this, SearchActivity.class));
				overridePendingTransition(R.anim.top_in, R.anim.no_anim);
			}
		});
		//Тухай товчлуур
		findViewById(R.id.title_info).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				startActivity(new Intent(MainActivity.this, InformationActivity.class));
				overridePendingTransition(R.anim.top_in, R.anim.no_anim);
			}
		});
		//Home буюу лого дээр дарах үйлдэл
		findViewById(R.id.home).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
			}
		});
		
		
		
		//Програмын үндсэн менюны үйлдлүүд
		findViewById(R.id.title_menu_1).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
//				Intent intent = new Intent(MainActivity.this, MainActivity.class); 
//				intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK); 
//				startActivity(intent);
			}
		});
		findViewById(R.id.title_menu_2).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(MainActivity.this, RentActivity.class); 
				intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK); 
				startActivity(intent);
				overridePendingTransition(R.anim.no_anim, R.anim.no_anim);
			}
		});
		findViewById(R.id.title_menu_3).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(MainActivity.this, NewApartmentActivity.class); 
				intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK); 
				startActivity(intent);
				overridePendingTransition(R.anim.no_anim, R.anim.no_anim);
			}
		});
		findViewById(R.id.title_menu_4).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(MainActivity.this, UBActivity.class); 
				intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK); 
				startActivity(intent);
				overridePendingTransition(R.anim.no_anim, R.anim.no_anim);
			}
		});
		findViewById(R.id.title_menu_5).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(MainActivity.this, AutomobileActivity.class); 
				intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK); 
				startActivity(intent);
				overridePendingTransition(R.anim.no_anim, R.anim.no_anim);
			}
		});
	}
	@Override
	public void onBackPressed() {
	   finish();
	   overridePendingTransition(R.anim.no_anim, R.anim.no_anim);
	}

}
